package com.mymarkdown.app.service.impl;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.mymarkdown.app.common.ResponseResult;
import com.mymarkdown.app.common.constant.Constant;
import com.mymarkdown.app.model.UserSettingInfo;
import com.mymarkdown.app.service.ObserverSettingService;
import com.mymarkdown.app.service.SystemSettingService;
import com.mymarkdown.app.util.ThreadPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.Optional;

/**
 * @author zenglun
 * @date 2021/12/15 2:53 下午
 * @description: TODO
 */
@Slf4j
@Service
public class SystemSettingServiceImpl implements SystemSettingService {


    @Autowired
    private ObserverSettingService observerSetting;

    @Autowired
    private CacheManager cacheManager;

    private Cache cache;

    @PostConstruct
    public void init() {
        cache = cacheManager.getCache(Constant.AllCacheKey.SAVE_SYSTEM_SETTING_CACHE_KEY);
    }

    @Override
    public ResponseResult setSystemSetting(UserSettingInfo userSettingInfo) {
        // 监视这个pojo对象属性是否发生变化，如果发生了变化，则找到对应处理事件
        observerSetting.observer(userSettingInfo);
        // 将其保存在缓存中
        cache.put(Constant.AllCacheKey.SAVE_SYSTEM_SETTING_CACHE_KEY, userSettingInfo);
        // 并异步持久化到磁盘中
        ThreadPool.getInstant().commit(() -> {
            //写入磁盘
            try {
                IoUtil.write(new FileOutputStream(Constant.AllFilePath.SYSTEM_SETTING_CONFIG_FILE),
                        true, JSON.toJSONString(userSettingInfo).getBytes(StandardCharsets.UTF_8));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                log.error("[SystemSettingServiceImpl]---[setSystemSetting],持久化系统参数失败,异常信息为:{}", e);
            }
        });
        return ResponseResult.ok("");
    }



    @Override
    public UserSettingInfo getOriginalInfo() {
        UserSettingInfo settingInfo = cache.get(Constant.AllCacheKey.SAVE_SYSTEM_SETTING_CACHE_KEY, UserSettingInfo.class);
        if (Objects.isNull(settingInfo)) {
            //从IO流中读取settingInfo信息
            String systemConfigStr = null;
            InputStream inputStream = null;
            try {
                inputStream = new FileInputStream(Constant.AllFilePath.SYSTEM_SETTING_CONFIG_FILE);
                systemConfigStr = IoUtil.read(inputStream, StandardCharsets.UTF_8);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                log.error("[ObserverSettingServiceImpl]---[getOriginalInfo],获取系统配置文件失败,异常信息为:{}", e);
                //设置一个默认的
                systemConfigStr = JSON.toJSONString(UserSettingInfo.defaultObj());
            } finally {
                Optional.ofNullable(inputStream).ifPresent(io -> {
                    try {
                        io.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        log.error("[ObserverSettingServiceImpl]---[getOriginalInfo],关闭读取流发生异常,异常信息为:{}", e);
                    }
                });
            }
            settingInfo = JSON.parseObject(systemConfigStr, UserSettingInfo.class);
            //存入
            cache.put(Constant.AllCacheKey.SAVE_SYSTEM_SETTING_CACHE_KEY, settingInfo);
        }
        return settingInfo;
    }
}
